<script setup>
import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
import SysUser from '@/views/SystemManage/SysUser/Child/AppUser/AppUser.vue'
import { computed, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import api from '@/api/index.js'
import { DeleteOutlined } from '@ant-design/icons-vue';
import { getOptions, getConsants } from '@/utils/index.js'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  },
})
// 弹窗标题
const title = computed(() => props.curRow.remark)
// 表单数据
const formData = ref({
  typeId: '',
  typeName: '',
  copyId: '',
  copyName: '',
  remark: '',
  persons: [],
})
// 是否显示弹窗
const show = ref(false);
// 同步表格数据到表单数据内
watch(() => props.curRow, async (val) => {
  let resObj = {}
  if (props.curRow.id && show.value) {
    const { resultObject } = await api.getSpszInfo({ id: props.curRow.id })
    resObj = resultObject
    formData.value = { ...formData.value, ...val, ...resObj }
  } else {
    formData.value = {
      typeId: '',
      typeName: '',
      copyId: '',
      copyName: '',
      remark: '',
      persons: [],
    }
  }
}, { deep: true, immediate: true })
// 弹窗显示状态切换时触发
const afterOpenChange = bool => {
  if (!bool) {
    formData.value = {
      typeId: '',
      typeName: '',
      copyId: '',
      copyName: '',
      remark: '',
      persons: [],
    }
    emits('close')
  }
};
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value, ...info,
      outBigTypeName: getConsants('approve_type', info.typeId),
    }
    await api.editSpsz(params)
    message.success('编辑成功');
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30);
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30);
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value, ...info,
      outBigTypeName: getConsants('approve_type', info.typeId),
    }
    await api.addSpsz(params)
    message.success('新增成功');
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30);
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30);
  }
}
// 表单提交，验证通过了
const onFinish = values => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
};
// 验证失败
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
// 打开弹窗
const open = () => {
  show.value = true;
};
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value
    .validateFields()
    .then(onFinish)
    .catch(onFinishFailed);
}
defineExpose({ open })

const addSpr = () => {
  formData.value.persons.push({
    personNo: '',
    personOpenId: '',
    personId: '',
    nickName: '',
  })
}

const delItem = (i) => {
  formData.value.persons.splice(i, 1)
} 
</script>

<template>
  <a-drawer destroyOnClose :maskClosable="false" :closable="false" v-model:open="show" class="custom-class"
    root-class-name="root-class-name" :title="title" placement="right" @after-open-change="afterOpenChange">
    <a-form ref="formRef" :model="formData" layout="vertical" autocomplete="off" @finish="onFinish"
      @finishFailed="onFinishFailed">
      <a-form-item label="审核类型" name="typeId" :rules="[{ required: true, message: '请选择' }]" v-if="false">
        <a-select v-model:value="formData.typeId" :options="getOptions('approve_type')" allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }" />
      </a-form-item>
      <a-form-item label="抄送人" name="copyId" :rules="[{ required: true, message: '请选择' }]">
        <SltFromTable :params="{ isAdmin: 1 }" v-model="formData.copyId" :nameValue="formData.copyName"
          :component="SysUser" :getRows="e => formData.copyName = e?.[0]?.nickName ?? ''"
          :fieldNames="{ name: 'nickName', id: 'memId' }" />
      </a-form-item>
      <a-form-item label="审批人" name="persons" :rules="[{ required: true, message: '请选择' }]">
        <div v-for="(item, index) in formData.persons" :key="item.id" class="spr-box">
          <DeleteOutlined class="del" @click="delItem(index)" />
          <a-form-item label="选择审批人" :name="['persons', index, 'personId']" :rules="{ required: true, message: '请选择' }">
            <SltFromTable :params="{ isAdmin: 1 }" v-model="item.personId" :nameValue="item.personName"
              :component="SysUser" :getRows="e => {
                formData.persons[index].personName = e?.[0]?.nickName ?? '';
                formData.persons[index].personOpenId = e?.[0]?.openId ?? '';
              }" :fieldNames="{ name: 'nickName', id: 'memId' }" />
          </a-form-item>
          <a-form-item label="排序" :name="['persons', index, 'personNo']" :rules="{ required: true, message: '请输入' }">
            <a-input-number  :min="1" v-model:value="item.personNo" allowClear />
          </a-form-item>
        </div>
        <a-button type="primary" @click="addSpr">新增审批人</a-button>
      </a-form-item>
      <a-form-item label="备注" name="remark" v-if="false">
        <a-input v-model:value="formData.remark" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex;gap: 5px;">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading">提交</a-button>
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>

<style lang="scss" scoped>
.spr-box {
  margin-bottom: 10px;
  border: 1px solid #eee;
  padding: 10px;
  padding-bottom: 0;
  border-radius: 4px;
  position: relative;

  .del {
    position: absolute;
    right: 10px;
    top: 10px;
    color: #e87171;
    cursor: pointer;
  }
}
</style>